<?php


namespace app\appapi\controller;


use app\common\controller\AlipayController;
use app\common\controller\PayController;
use app\common\model\ArticleModel;
use app\common\model\MoneyLogModel;
use app\common\model\OrderModel;
use app\common\model\ReceiveOrderModel;
use app\common\model\RechargeModel;
use cmf\controller\RestUserBaseController;
use think\db\Query;
use think\Request;

class UserController extends RestUserBaseController
{
    public function logout()
    {
        session('USER_ID', null);
        session('USER_TOKEN', null);
        $this->success('退出成功');
    }

    /**
     * add_time: 1591612465
     * avatar: ""
     * email: ""
     * exclusive: "0.00"
     * frozen_money: "0.00"
     * gender: 1
     * id: 5925
     * integral: "0.00"
     * inviter_code: "NTkyNQ=="
     * inviter_id: 0
     * inviter_num: 0
     * is_api: "0"
     * job_number: "1001"
     * last_login_time: 1592535130
     * login_time: 1592552459
     * money: "0.10"
     * nickname: "15558164462_4709"
     * phone: "15558164462"
     * qq: "511895959"
     * remark: ""
     * service_id: 1
     * site_id: 3
     * username: "15558164462_9816"
     * wechat: ""
     * wechat_qr: ""
     */
    public function get_user_info()
    {
        $this->user['last_login_time'] = date('Y-m-d H:i', $this->user['last_login_time']);
        $this->success('userinfo', $this->user);
    }


    public function get_user_default()
    {
        $article = ArticleModel::where('cate', 1)->order('id desc')->select();
        $article2 = ArticleModel::where('cate', 4)->order('id desc')->select();
        for ($i = 0; $i < 5; $i++) {
            $order_status_num[] = OrderModel::where(['user_id' => $this->userId, 'order_status' => $i])->count();
        }

        $service_info = [];
        $user_info = $this->user;
        $this->success('ok', compact('article', 'article2', 'order_status_num', 'service_info', 'user_info'));
    }

    /**
     * 资金明细
     * @param $p
     * @param array $time
     *
     * add_time: 1592639204
     * frozen_money: "0.00"
     * id: 102820
     * info: "用户[15558164462_4709]支付宝在线充值"
     * integral: "0.00"
     * log_no: "2020062015464459970"
     * money: "0.01"
     * name: "在线充值"
     * nickname: "15558164462_4709"
     * now_money: "0.11"
     * pay_type: "在线充值"
     * user_id: 5925
     *
     */
    public function get_money_log_list()
    {
        $list = MoneyLogModel::where(function (Query $query) {
            $query->where('user_id', $this->userId);
            $param = $this->request->param();
            if (isset($param['times']) && !empty($param['times'])) {
                $query->whereBetweenTime('add_time', strtotime($param['times'][0]), strtotime($param['times'][1]));
            }
        })->order('id desc')->paginate();
        $this->success('ok', $list);
    }

    /**
     * 底单申请
     */
    public function get_receive_order()
    {
        $list = ReceiveOrderModel::where('user_id', $this->userId)->select();
        $this->success('ok', $list);
    }

    /**
     * 添加底单
     */
    public function add_receive_order(Request $request)
    {
        $data = [
            'order_no_nums' => count($request->order_nos_arr),
            'order_nos' => $request->order_nos,
            'email' => $request->email,
            'nickname' => $this->user['user_nickname'],
            'phone' => $this->user['user_login'],
            'user_id' => $this->userId,
            'add_time' => time()
        ];
        if (ReceiveOrderModel::create($data)) {
            $this->success('ok');
        } else {
            $this->error('申请失败');
        }
    }

    public function edit_user_info(Request $request)
    {
        $password = $this->user['password'];
        if (!cmf_compare_password($request->old_password, $password)) {
            $this->error('原密码不正确');
        }
        if (!cmf_check_pass($request->password)) {
            $this->error('密码必须是6-20位数字字母组成');
        }
        $this->user->save(['password' => cmf_password($request->password)]);
        session('USER_ID', null);
        $this->success('修改成功，请重新登录');

    }

    public function user_recharge(Request $request)
    {
        if ($request->money <= 0) {
            $this->error('请确认充值金额');
        }
        $order_no = cmf_get_order_sn();
        $data = [
            'user_id' => $this->userId,
            'nickname' => $this->user['user_nickname'],
            'phone' => $this->user['user_login'],
            'money' => $request->money,
            'addtime' => time(),
            'order_no' => $order_no,
        ];
        if (!RechargeModel::create($data)) {
            $this->error('下单失败');
        }
        $alipay = new AlipayController();
        $res = $alipay->unifiedorder($order_no, '在线充值', $request->money);
        $data['orderString'] = $res;
        $this->success('ok', $data);
    }

    public function recharge()
    {
        $res = (new PayController())->index();
        $this->success('ok', $res);
    }
    
    public function fm_recharge()
    {
        $amount = $this->request->param('amount', 0, 'trim');
        if ($amount < 1) $this->error('最低支付 1 元');
        
        $paySettings =  cmf_get_option('pay_settings');
        if (empty($paySettings['mchid']) || empty($paySettings['secret']) || empty($paySettings['notify'])) $this->error('支付配置错误，请联系管理');
        
        $orderNo = cmf_get_order_sn();
        $data = [
            'user_id' => $this->userId,
            'nickname' => $this->user['user_nickname'],
            'phone' => $this->user['user_login'],
            'money' => $amount,
            'addtime' => time(),
            'order_no' => $orderNo,
        ];
        if (!RechargeModel::create($data)) {
            $this->error('订单创建失败');
        }
        
        $merchantNum = $paySettings['mchid']; // 商户号, 商户后台的用户中心页面查看
        $secret = $paySettings['secret']; // 商户密钥, 商户后台的用户中心页面查看
        $api_url = 'http://api-ahchzrimpk3k.zhifu.fm.it88168.com/api/startOrder'; // 接口地址， 商户后台的用户中心页面查看
        $payType = $this->request->param('payType'); // 查看支付接口文档说明payType的取值
        if (!in_array($payType, ['alipay', 'wechat'])) $this->error('支付方式错误');
        $notifyUrl = $paySettings['notify']; // xxxx修改为您自己用来接收支付成功的公网地址
        $returnUrl = ''; // 'http://xxxx/return_url.php'; # 支付成功您想展示给顾客看到的页面地址
        $returnType = "json"; // 接口返回方式 page为直接跳转到支付页面，不传返回json
        $sign = $this->sign ( array (
        		$merchantNum,
        		$orderNo,
        		$amount,
        		$notifyUrl,
        		$secret
        ) );
        $native = array (
    		"merchantNum" => $merchantNum,
    		"payType" => $payType,
    		"amount" => $amount,
    		"orderNo" => $orderNo,
    		"notifyUrl" => $notifyUrl,
    		"returnUrl" => $returnUrl,
    		"sign" => $sign,
    		"returnType" => $returnType,
    		"attch"=> $this->userId,//附加信息，原样返回
        );
        
        $param = http_build_query ( $native );
        $return = $this->http_request ( $api_url, $param, 'application/x-www-form-urlencoded;charset=utf-8' );
        return $return;
    }
    protected function sign($data_arr) {
	    return md5 ( join ( '', $data_arr ) );
    }
    protected function http_request($url, $post_data=array(), $header='Content-Type: application/json'){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 返回最后的Location
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            $header,
            'Content-Length: ' . strlen($post_data)
        ));
        $contents = curl_exec($ch);
        curl_close($ch);
        return $contents;
    }

}